<?php
namespace Admin\Controller;
use Think\Controller;
class BaseController extends Controller
{

    public function __construct(){
    

        parent::__construct();//先执行父级的构造函数
        //如果重写了Construct的构造函数 ，则必须添加parent::__construct();
        //构造函数

        $this->check_login();
        $this->check_level();
}
    //判断是否有访问的权限
    private function check_level(){
        $ignore_level = array("Login","Base","Index");
        if(!in_array(CONTROLLER_NAME,$ignore_level)){
        $crontroller_id =0;
        $action_id = 0;
        $crontroller_id = M("level")->where(array("acontroller" => CONTROLLER_NAME))->getfield("id");
        $action_id = M("level")->where(array("acontroller" => ACTION_NAME,"pid" => $crontroller_id))->getfield("id");
        $level = session("level");

        if(!in_array($crontroller_id,$level) || !in_array($action_id,$level)){

            $this->redirect("Base/error");die;
        }
        }
    }

    public function error(){
        $this->display("Public/error");

    }
    //验证登录
    protected function check_login(){

        $ignore=array('code','check_verify');//忽略方法

        if(CONTROLLER_NAME=='Login'){
            if(session("?username") || !empty(cookie("username"))){
                //如果session不为空，就把cookie的值赋给session
                if(!session("?username") && !empty(cookie("username"))){
                    session("username",cookie("username"));
                    session("level",cookie("level"));
                }
                $this->redirect('index/index');
            }
        }else{
            if(!in_array(ACTION_NAME,$ignore)){
            if(!session("?username") && empty(cookie("username"))){
                $this->redirect('login/login');
            }
        }
    }
    }
    //退出
    public function loginout(){


        cookie('username',null); //销毁下标为username的cookie的值
        cookie('password',null);
        cookie('level',null);
        session(null);//销毁所有的session
        $this->redirect('login/login');
    }
    //验证码
    public function code(){
        $config = array(
        'fontSize' => 16, // 验证码字体大小
        'length' => 4, // 验证码位数
        'useNoise' => ture, // 关闭验证码杂点
        'useImgBg' => true, //背景图验证码
        );

         $Verify = new \Think\Verify($config);
         $Verify->entry();

    }

    /*public function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }*/

    public function check_verify(){

        $code = I('post.code');

        $verify = new\Think\Verify();
        $verify->reset = false;//防止验证码验证一次后失效
        if($verify->check($code)){
            $message=array(
                'error' => 0,
                'message' => '验证成功',
            );
        }else{
            $message=array(
                'error' => 1,
                'message' => '验证失败',
            );
        }
        $this->ajaxReturn($message);
    }
}
?>